package com.skd.mall.product.service.impl;

import com.skd.mall.product.dao.CategoryBrandRelationDao;
import com.skd.mall.product.entity.CategoryBrandRelationEntity;
import com.skd.mall.product.service.CategoryBrandRelationService;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.skd.common.utils.PageUtils;
import com.skd.common.utils.Query;

import com.skd.mall.product.dao.BrandDao;
import com.skd.mall.product.entity.BrandEntity;
import com.skd.mall.product.service.BrandService;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String)params.get("key");
        QueryWrapper<BrandEntity> brandEntityQueryWrapper = new QueryWrapper<BrandEntity>();
        if(key != null && key.length() != 0){
            IPage<BrandEntity> page = this.page(
                    new Query<BrandEntity>().getPage(params),
                    brandEntityQueryWrapper.eq("brand_id",key).or().like("name",key)
            );
            return new PageUtils(page);
        }
            IPage<BrandEntity> page = this.page(
                    new Query<BrandEntity>().getPage(params),
                    brandEntityQueryWrapper
            );
            return new PageUtils(page);
    }

    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;
    QueryWrapper<CategoryBrandRelationEntity> wrapper = new QueryWrapper<>();
    @Override
    public void updateDetail(BrandEntity brand) {
        //更新原始数据
        this.updateById(brand);
        //更新冗余数据
        wrapper.eq("brand_id",brand.getBrandId());
        List<CategoryBrandRelationEntity> list = categoryBrandRelationDao.selectList(wrapper);
        list.stream().forEach(categoryBrandRelationEntity -> {
            if(!categoryBrandRelationEntity.getBrandName().equals(brand.getName())){
                categoryBrandRelationEntity.setBrandName(brand.getName());
                categoryBrandRelationDao.updateById(categoryBrandRelationEntity);
            }
        });
    }

}